import React, { useState } from 'react';
import { Select } from '@alifd/next';
import { AutoCompleteProps } from '@alifd/next/types/select';

const { AutoComplete } = Select;

interface InputSelectProps extends AutoCompleteProps {
  onFetch: (value: string) => Promise<any>;
  labelField: string;
  valueField: string;
}


/**
 * 输入远程获取数据
 * @returns
 */
function InputSelect({onFetch, labelField, valueField, onChange,  ...props}: InputSelectProps) {
  const [data, setData] = useState([]);

  const handleChange = async (value: any, actionType: string, item: any): Promise<void> =>  {
    const res = await onFetch(value);
    setData(res.map((item: any) => ({
      label: item[labelField],
      value: item[valueField],
      item,
    })));
    onChange?.(value, actionType, item);
  }

  return (
    <AutoComplete
      style={{ width: '100%' }}
      filterLocal={false}
      onChange={handleChange}
      dataSource={data}
      {...props}
    />
  );
}

export default InputSelect;
